package com.google.code.sysarch.v3.elves;

import java.awt.Graphics2D;

public class Reindeer extends Thread implements Drawable {
	
	static int deerNeeded = 4;
	static int deerWaiting = 0;
	static boolean deerReleased = false;
	static int deerTotal = 0;
	
	Sprite sprite;
	PathWalker myWalker;
	int offset_x;
	int offset_y;
	long thread_timer = 0;
	boolean running;
	private int hunger;
	
	Reindeer(String filename) {
		this.sprite = SpritePool.get().getSprite(filename);
		this.hunger = 100;
		deerTotal++;
	}
	
	public void run() {
		thread_timer = System.nanoTime();
		running = true;
		double delta;
		PathWalker myWalker = Game.get().getMap().getPathWalker(this);
		myWalker.setSpeed(Math.random()*100+100);		
		
		while (running) {
			delta = (double)(System.nanoTime() - thread_timer) / 1000000000L;
			Game.get().getMap().updateSingle(myWalker, delta);
			thread_timer = System.nanoTime();			
			try {
				sleep(30);
			} catch (InterruptedException e) { }
		}		
	}

	public void setOffset(int x, int y) {
		this.offset_x = x;
		this.offset_y = y;
	}
	
	public void draw(Graphics2D g, int x, int y) {
		this.sprite.draw(g, x+offset_x, y+offset_y);		
	}
	
	public void kill() {
		this.running = false;
	}
	
	public String toString() {
		return "Elf "+this.getName();
	}
	
	public boolean onEvent(PathWalker p, String event, WayPoint caller, WayPoint helper) {
		if (event.length() > 11 && event.substring(0, 11).equals("checksanta ")) {
			if (hunger < 0) {
				Game.get().getMap().move(p, event.substring(11, event.length()));
			}
		} else if (event.equals("fly")) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) { }	
			this.hunger = (int)(Math.random()*150 + 75);
			return true;
		} else if (event.equals("eat")) {
			if (hunger > 0) {
				try {
					int duration = (int)(Math.random()*4000 + 1000);
					Thread.sleep(duration);
					hunger -= duration/120;
				} catch (InterruptedException e) { }
			}
		} else if (event.equals("gather")) {
			synchronized (Game.monitor) {
				deerWaiting++;
				p.setPosition(p.getX()+deerWaiting*5, p.getY()+deerWaiting*2);
				do {
					if (Game.get().santa.isSleeping() && deerWaiting >= deerNeeded) {
						deerReleased = true;
						Game.get().santa.wakeUp("Reindeer");
						Game.monitor.notifyAll();
					} else {
						try {
							Game.monitor.wait();
						} catch (InterruptedException e) { }						
					}
				} while (!deerReleased);
				deerWaiting--;
				if (deerWaiting == 0) {
					deerReleased = false;
				}
			}			
			Game.get().getMap().move(p, "Schlittenzug");			
			return true;
		}
		return false;
	}
	
}